﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AudioController : MonoBehaviour {

	public AudioClip testingA;
	public AudioSource musicA;
	public List<AudioSource> babyLaugh = new List<AudioSource> ();
	public int babyLaughNumber;
	public AudioSource babyVoice;
	public AudioSource babyFeeding;
	public AudioSource babyBurpLong;
	public AudioSource babyBurpShort;
	public float laughInterval;
	public float laughIntervalMin;
	public float laughIntervalMax;
	public float laughPitchShift;
	public float laughPitchShiftMin;
	public float laughPitchShiftMax;
	public float chanceOfTalking;
	public float talkingRoll;
	public float startTime;
	public bool isHappy;

	MoodController moodController;

	// Use this for initialization
	void Start () {

		moodController = Camera.main.GetComponent<MoodController>();	
		moodController.AddMoodChangedCallback(ChangeMood);

		// initialize laughter variables
		laughInterval = Random.Range(laughIntervalMin, laughIntervalMax);
		startTime = Time.time;
	}

	public void OnDisable()
	{
		moodController.RemoveMoodChangedCallback(ChangeMood);
	}

	protected void ChangeMood( MoodController.MoodState mood)
	{
		// change audio
		switch(mood)
		{
			case MoodController.MoodState.EATING:
			// play sound 
			isHappy = false;
			babyFeeding.Play();
			break;

			case MoodController.MoodState.HAPPY:
			// play sound
			babyFeeding.Stop();
			isHappy = true;
			break;

			case MoodController.MoodState.RELAXED:
			isHappy = false;
			babyFeeding.Stop();
			break;

			default:
			isHappy = false;
			babyFeeding.Stop();
			break;
		}
	}
	
	// Update is called once per frame
	void Update () {
		if(isHappy)
		{
			if (startTime + laughInterval < Time.time)
			{
				talkingRoll = Random.Range(0, 1.0f);
				//play the laugh sound
				if (chanceOfTalking > talkingRoll){
					babyLaughNumber = Random.Range(0, babyLaugh.Count);
					laughPitchShift = Random.Range(laughPitchShiftMin, laughPitchShiftMax);
					babyLaugh[babyLaughNumber].pitch = laughPitchShift;
					babyLaugh[babyLaughNumber].Play();
				}else{
					babyVoice.Play();
				}

				laughInterval = Random.Range(laughIntervalMin, laughIntervalMax);
				startTime = Time.time;
			}
		}
	}
}
